package net.cyue.nest.nestjava.platform.tomcat;

import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import net.cyue.nest.nestjava.common.data.http.HTTPRequestBody;
import net.cyue.nest.nestjava.common.data.http.HTTPRequestParams;
import net.cyue.nest.nestjava.common.enums.RequestMethod;
import net.cyue.nest.nestjava.common.util.InputUtil;
import net.cyue.nest.nestjava.core.adapter.AbstractHTTPRequest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class TomcatHTTPRequest
        extends AbstractHTTPRequest<HttpServletRequest>
{
    public TomcatHTTPRequest(ServletRequest request) {
        this.request = (HttpServletRequest) request;
        try {
            this.request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public String scheme() {
        return this.request.getScheme();
    }

    @Override
    public RequestMethod method() {
        return RequestMethod.valueOf(this.request.getMethod().toUpperCase());
    }

    @Override
    public String uri() {
        return this.request.getRequestURI();
    }

    @Override
    public String path() {
        return this.request.getContextPath();
    }

    @Override
    public HTTPRequestParams params() {
        final var params = this.request.getParameterMap();
        return new HTTPRequestParams(params);
    }

    @Override
    public HTTPRequestBody body() throws IOException {
        final var reader = this.request.getReader();
        final var bodyString = InputUtil.readString(reader);
        var contentType = this.getHeader("Content-Type");
        if (contentType == null) {
            contentType = "";
        }
        if (contentType.contains("application/json")) {
            return HTTPRequestBody.fromJSONString(bodyString);
        } else if (contentType.contains("form-data")) {
            // TODO 读取数据
            return new HTTPRequestBody();
        } else {
            return HTTPRequestBody.fromQueryString(bodyString);
        }
    }

    @Override
    public String getHeader(String name) {
        return this.request.getHeader(name);
    }

    @Override
    public String getParameter(String name) {
        return this.request.getParameter(name);
    }

    @Override
    public HttpSession getSession() {
        return this.request.getSession();
    }
}


